<template>
	<view class=" imgupload">
		<view class=" flex_wrap">
			<view class="imgs-view" v-for="(v,i) in imgArray" :mode="'aspectFill'" :key="i">
				<image @click="preview(v,i)" :src="v"></image>
				<view class="del-btn" @click="delImg(i)">

					<image :src="imgUrl+'/uploading/whiteClose.png'" class="flex_xy_centerImage"
						style="margin: 0;width: 39rpx;height: 39rpx;"></image>
					<!-- <view v-if="!v">{{title}}</view> -->
				</view>
			</view>
			<view v-if="imgArray.length<imgCount" class="upload-img-view flex_xy_center" @click="upPhoto">
				<!-- <image
					src="">
				</image> -->
				<image :src="imgUrl+'/uploading/addImage.png'" class="flex_xy_centerImage"></image>
				<view class="tilteView">
					<view class="flex_xy_centerTitle">{{title}}</view>
					<view v-if="tag" class="redView">*</view>
				</view>
			</view>

		</view>
		<view v-if="!closeTip&&!tipObj.prompt" class="imgupload__tip">* 最多上传{{imgCount}}张图片(<label> {{imgArray.length}}
			</label>/{{imgCount}})</view>

	</view>
</template>

<script>
	export default {
		name: 'imgUpload',
		props: {

			type: {
				type: String,
				default: 'other'
			},
			imgArr: { //图片数组
				type: [Array],
			},
			title: {
				type: String,

			},
			uploadImgCount: { //一次上传图片数
				type: String,
				default: '1'
			},
			imgCount: { //可上传图片总数
				type: String,
				default: '3'
			},
			imgSize: { //图片大小 单位M
				type: Number,
				default: 4
			},
			formData: {
				type: Object,
				default: function() {
					return {}
				}
			},
			imgType: { //如果是小程序，这个值则没用作用
				type: [Array],
				default: function() {
					return ['jpeg', 'png', 'jpg']
				}
			},
			tag: {
				type: Boolean,
				default: false
			},
			closeTip: {
				type: Boolean,
				default: false
			},
			loading: {
				type: Boolean,
				default: true
			},
			url: { //上传图片Url
				type: String,
			},
			async: {
				type: Boolean,
				default: false
			},
			header: {
				type: Array,
				default: function() {
					return []
				}
			},
			previewMany: { //多图预览
				type: Boolean,
				default: false
			},
			pressImg: { //压缩图片 H5暂不支持压缩api
				type: Number,
				default: -1
			},
			config: {
				type: Object,
				default: function() {
					return {
						delIcon: '', //删除图片icon
						resultTip: true, //结果提示
						resultType: '1', //结果展示类型
						loadIcon: '', //加载时的图标
						loadText: '' //加载时的文字
					}
				}
			}
		},
		data() {
			return {
				imgArray: [],
				title: '',
				canUpCount: '',
				startUpload: false,
				tipObj: {
					prompt: '',
					typeColor: '#009100',
					must: false, //必须要存在的时候
					success: '#009100', //成功-#009100; 可自定义修改
					warning: '#bb9300', // 警告 -#bb9300; 可自定义修改
					error: '#FF0000' // 失败--#FF0000; 可自定义修改
				},
				headers: {},
				curPlatform: '',
				currIndex: null,
				ossData: {}, //oss参数
				imgUrl: this.$mConfig.staticUrl,
			}
		},
		created() {
			this.imgArray = this.imgArr || [];

			// this.formDataGet()
			this.canUpCount = Number(this.uploadImgCount);


		},
		watch: {
			imgArr(n, o) {
				this.imgArray = n || [];

			},
			imgCount(n, o) {
				this.uploadImgCount = n;
				this.canUpCount = Number(this.uploadImgCount);
			},

		},
		methods: {
			//上传凭证
			formDataGet() {
				let that = this
				uni.request({
					//url: 'https://pm.lidashine.com/get-oss-sign', //oss获取参数接口地址。
					url: this.$mConfig.imgURL,
					complete: (result) => {
						let res = JSON.parse(result.data.data);
						that.ossData = res
					}
				})
			},
			//预览图片
			preview(obj, index) {
				if (this.previewMany) {
					let urls = [];
					urls.push(obj.url)
					this.imgArray.map(item => {
						if (obj.id != item.id) {
							urls.push(item.url);
						}
					})
					uni.previewImage({
						urls: urls
					});
				} else {
					// 预览图片(单张)
					uni.previewImage({
						urls: [obj.url]
					});
				}
			},
			//删除图片
			delImg(i) {
				const _this = this;
				uni.showModal({
					// title: '提示',
					content: '是否删除这张照片？',
					success: function(res) {
						if (res.confirm) {
							_this.imgArray.splice(i, 1);
							_this.$emit('result', _this.imgArray)
						} else if (res.cancel) {}
					}
				});
			},
			// 随机生成文件名
			random_string(len) {
				len = len || 32;
				var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
				var maxPos = chars.length;
				var pwd = '';
				for (let i = 0; i < len; i++) {
					pwd += chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},
			//上传图片
			upPhoto() {
				let that = this;
				uni.showActionSheet({
					itemList: ['拍照上传', '从相册中选择'],
					success: function(res) {
						console.log(res)
						if (res.tapIndex == 0) {
							uni.chooseImage({
								count: Number(that.canUpCount) - that.imgArray.length,
								sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['camera'], //从相册选择
								success: function(res) {
									if (res) {
										let filePath = res.tempFilePaths[0]
										let nameStr = that.random_string(8) + '.' + filePath.split(
											'.').pop();
										if (res.tempFiles) {
											for (let item of res.tempFiles) {
												if (item.size > (that.imgSize * 1024 * 1024)) {
													uni.showToast({
														title: `图片不能大于${that.imgSize}M`,
														icon: 'none'
													})
													return false;
												}
												if (item.type) {
													let r = that.imgType.some(v => {
														let type = item.type.split('/');
														if (type.length)
															return (v === type[1]);
													});
													if (!r) {
														uni.showToast({
															title: `只允许上传${that.imgType}的类型`,
															icon: 'none'
														})
														return false;
													}
												}
											}
										}


										that.updataImg(filePath, nameStr)
									}
								},
								complete(e) {
									console.log(e)
								}
							});
						} else if (res.tapIndex == 1) {

							uni.chooseImage({
								count: Number(that.canUpCount) - that.imgArray.length,
								sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['album'], //从相册选择
								success: function(res) {
									if (res) {


										if (res.tempFiles) {
											for (let [index, item] of res.tempFiles.entries()) {
												if (item.size > (that.imgSize * 1024 * 1024)) {
													uni.showToast({
														title: `图片不能大于${that.imgSize}M`,
														icon: 'none'
													})
													return false;
												}
												if (item.type) {
													let r = that.imgType.some(v => {
														let type = item.type.split('/');
														if (type.length)
															return (v === type[1]);
													});
													if (!r) {
														uni.showToast({
															title: `只允许上传${that.imgType}的类型`,
															icon: 'none'
														})
														return false;
													}
												}
												let filePath = res.tempFilePaths[index]

												let nameStr = that.random_string(8) + '.' + res
													.tempFilePaths[index].split('.').pop();

												that.updataImg(filePath, nameStr)
											}
										}



									}
								}
							});
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},

			updataImg(filePath, nameStr) {
				uni.showLoading();
				let date = new Date();
				let allData = date.getFullYear() + '-' + date.getMonth() + 1 + '-' + date.getDate();
				let shopid = uni.getStorageSync('shop')
				let id = 0
				if (!shopid) {
					id = 0
				} else {
					id = shopid.id
				}
				let key = 'img/' + id + '/' + this.type + '/' + allData + '/' + nameStr
				uni.uploadFile({
					// url: this.$mConfig.baseUrl+ '/minio/upload',
					url: this.$mConfig.baseUrl + '/sys/oss/upload',
					filePath: filePath,
					fileType: 'image',
					name: 'file',
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode != 200) {
							return;
						}
						let resObj = JSON.parse(res.data);
						let imgurl = resObj.data.url;
						this.imgArray.push(imgurl)
						this.$emit('result', this.imgArray)
						uni.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 1000
						})

						// alert(ossRes.host+"/"+encodeURIComponent(fileName));

					},
					fail: (err) => {
						uni.hideLoading();
						console.log('uploadImage fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			},



		}
	}
</script>


<style scoped>
	.w-100 {
		width: 100%;
	}

	.flex {
		/* 转为弹性盒模型*/
		display: flex;
	}

	.flex_bet {
		/* 两端左右*/
		display: flex;
		justify-content: space-between;
	}

	.flex_wrap {
		/* 转为弹性盒模型并自动换行*/
		display: flex;
		flex-wrap: wrap;
	}

	.flex_xy_center {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
	}

	.upload-img-view {
		width: 192rpx;
		height: 192rpx;
		background: #F9F9F9;
		border-radius: 15rpx 15rpx 15rpx 15rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;


	}

	.upload-img-view>image {
		width: 70rpx;
		height: 70rpx;
	}

	.upload-txt {
		font-size: 24rpx;
		color: #FFFFFF;
	}

	.imgs-view {
		height: 192rpx;
		width: 192rpx;
		border-radius: 10rpx;
		margin-right: 1.8%;
		margin-bottom: 16rpx;
		border: 1rpx solid #F1F1F1;
		box-sizing: border-box;
		position: relative;

	}

	.result {
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 45rpx;
		font-size: 26rpx;
		left: 0;
		background-color: rgba(0, 0, 0, .6);
		text-align: center;
		line-height: 45rpx;
		border-bottom-left-radius: 10rpx;
		border-bottom-right-radius: 10rpx;
	}

	.result>.success {
		color: #00b900;
	}

	.result>.error {
		color: #b52e25;
	}

	.uploading {
		position: absolute;
		background-color: rgba(0, 0, 0, .5);
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		text-align: center;
		line-height: 100%;
		z-index: 999;
	}

	.uploading image {
		width: 60rpx;
		height: 60rpx;
		z-index: 1000;
		animation: rotation .6s linear infinite;
		-moz-animation: rotation .6s linear infinite;
		-webkit-animation: rotation .6s linear infinite;
		-o-animation: rotation .6s linear infinite;
	}


	@keyframes rotation {
		from {
			-webkit-transform: rotate(0deg);
			transform: rotate(0deg);
			-moz-transform: rotate(0deg);
			-o-transform: rotate(0deg);
		}

		to {
			-webkit-transform: rotate(360deg);
			transform: rotate(360deg);
			-moz-transform: rotate(360deg);
			-o-transform: rotate(360deg);
		}
	}

	.imgs-view>image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
	}

	.imgupload__tip {
		margin: 19rpx auto;
		font-weight: 400;
		font-size: 23rpx;
		color: #FF211F;
		line-height: 23rpx;

	}

	.imgupload__tip>label {
		color: #474747;
	}

	.del-btn {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		width: 39rpx;
		height: 39rpx;
		z-index: 98;
	}

	.del-btn>image {
		width: 100%;
		height: 100%;
		display: flex;
	}

	.css2 {
		border-style: solid;
		border-width: 0px 0px 100px 100px;
		border-color: transparent transparent blue transparent;
		width: 0px;
		height: 0px;
	}

	.flex_xy_centerImage {
		margin-top: 38rpx;
		margin-bottom: 26rpx;
		width: 46rpx !important;
		height: 46rpx !important;
	}

	.flex_xy_centerTitle {
		font-weight: 400;
		font-size: 23rpx;
		color: #999999;
		line-height: 23rpx;
		text-align: center;
		line-height: 1.5;
	}

	.redView {
		font-weight: 400;
		font-size: 27rpx;
		color: #FF211F;
		line-height: 27rpx;
	}

	.tilteView {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
	}
</style>